<?php

class shopController extends manageController {
    public function __construct() {
        if (!isset($_SESSION['zp_shop']['islogin']) || empty($_SESSION['zp_shop']['islogin'])) {
            Tools::AlertTxt('?md=shop&cl=login&at=login', '请先登录');
            exit;
        }
    }

    public function homeAction() {
        $shop_no = $_SESSION['zp_shop']['store_id'];
        # 待指派
        $ordersCount0 = $this->model->getStatusTotal(0);

        # 已指派
        $ordersCount1 = $this->model->getStatusTotal(1);

        # 待接单
        $ordersCount2 = $this->model->getStatusTotal(2);

        # 待取货
        $ordersCount3 = $this->model->getStatusTotal(3);

        # 配送中
        $ordersCount4 = $this->model->getStatusTotal(4);

        # 完成
        $ordersCount5 = $this->model->getStatusTotal(5);

        # 异常
        $ordersCount6 = $this->model->getStatusTotal(6);

        $ordersCount100 = $this->model->getStatusTotal(100);
        # 骑手
        $sql_riders = " SELECT count(id) as num FROM `riders` WHERE (`status`=1 or status = 4) and service_shop_no = $shop_no ";
        $orders7 = $this->model->getAny($sql_riders);
        if (!empty($orders7)) {
            while ($row = mysqli_fetch_array($orders7, MYSQLI_ASSOC)) {
                $riders = $row;
            }
        }
        $ordersCount7 = $riders['num'];
        $num = ['ordersCount0'=>$ordersCount0,'ordersCount1'=>$ordersCount1,'ordersCount2'=>$ordersCount2,'ordersCount3'=>$ordersCount3,
                'ordersCount4'=>$ordersCount4,'ordersCount5'=>$ordersCount5,'ordersCount6'=>$ordersCount6,'ordersCount7'=>$ordersCount7,
                'ordersCount100'=>$ordersCount100];
        $this->view->setVariable("num", $num);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /*
     * 未指派
     */
    public function ordersAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);
        $SearchArr['order_status'] = 0;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);

        $ridersWhere = array("AND" => array("=" => array("initiate" =>1,"status" =>1,'isdeleted'=>0,'service_shop_no'=>$_SESSION['zp_shop']['store_id'])));
        $orderby = array('id'=>'desc');
        $ridersList = $this->model->getAll($ridersWhere, 'riders', $orderby);
        $this->view->setVariable("ridersList", $ridersList);

        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /*
     * 订单详情包含指派历史记录，异常记录
     */
    public function orderdetailAction() {
        $table = "orders";
        $id = (!empty($this->params['id'])) ? $this->params['id'] : '';
        //抓列表
        if (!empty($id)){
            $row=$this->model->getItemById($id,$table);
            if($row['status'] == 0){
                $s = 100;
            }elseif($row['status'] == 7){
                $s = 6;
            }elseif($row['status'] == 100){
                $s = 900;   # Data Data::$_au[2]; 下标等于9 为了区分 这里指定900
            }else{
                $s = $row['status'];
            }
            $this->view->setVariable("s", $s);
            $where = array("AND" => array("=" => array("orders_id" => $row['id'],"status" => 1,"isdeleted" => 0)));
            $orderby = array('id'=>'asc');
            $products=$this->model->getAll($where, 'orders_product', $orderby);
            $row['products']=$products;

            $coupons=$this->model->getAll($where, 'orders_coupon', $orderby);
            $row['coupons']=$coupons;

            $where = array("AND" => array("=" => array("orders_id" => $row['id'])));
            $orderby = array('updatedt'=>'desc');
            $express_orders = $this->model->getAll($where, 'orders_express', $orderby);
            $row['express_orders']=$express_orders;

            # 筛选 门店修改地址
            $where = array('AND'=>array('='=>array('orders_id'=>$row['id'],'createid' => $_SESSION['zp_shop']['store_id'])));
            $orderby = ['createdt'=>'asc'];
            $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);
            if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0){
                foreach($shop_delivery_address as $k => $sdd){  # 拼装新老地址
                    if($k == 0){
                        $shop_delivery_address[$k]['old_receiver_name'] = $row['receiver'];
                        $shop_delivery_address[$k]['old_receiver_tel'] = $row['receiver_tel'];
                        $shop_delivery_address[$k]['old_receiver_address'] = $row['receiver_address'];
                    } else{
                        $shop_delivery_address[$k]['old_receiver_name'] = $shop_delivery_address[$k-1]['receiver_name'];
                        $shop_delivery_address[$k]['old_receiver_tel'] = $shop_delivery_address[$k-1]['receiver_tel'];
                        $shop_delivery_address[$k]['old_receiver_address'] = $shop_delivery_address[$k-1]['receiver_address'];
                    }
                }
                rsort($shop_delivery_address);
                # 拿到最新可用的地址
                $row['shop_delivery_address'] = $shop_delivery_address;
                $row['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
                $row['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
                $row['receiver'] = $shop_delivery_address[0]['receiver_name'];
                $row['distance'] = $shop_delivery_address[0]['distance'];
                $row['lat'] = $shop_delivery_address[0]['lat'];
                $row['lng'] = $shop_delivery_address[0]['lng'];
            }else{
                $row['upAddress']['receiver_name'] = $row['receiver'];
                $row['upAddress']['receiver_tel'] = $row['receiver_tel'];
                $row['upAddress']['receiver_address'] = $row['receiver_address'];
            }

            foreach ($row['express_orders'] as &$exp){
                unset($exp['tip']);
                unset($exp['tip_remark']);
                $where = array('AND'=>array('='=>array('order_no' => $exp['shop_express_no'],'shop_no' => $exp['shop_no'],'status' => 1,'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where, 'tip_list');
                if($data){
                    foreach($data as $k=>$t){
                        $exp['tip'] += $t['price'];
                        $exp['tip_remark'] .= isset($t['tip_remark']) ? '备注'.($k+1).':'.$t['tip_remark'] :''.' ';
                    }
                }
                if($exp['status'] == $row['status']){
                    $row['tip'] = $exp['tip'];
                    $row['tip_remark'] = $exp['tip_remark'];
                    $row['shop_express_remark'] = $exp['shop_express_remark'];
                }
            }

            $this->view->setVariable("row", $row);
        }
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function order_delivery_infoAction(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $OrderExpressData = $this->model->getItemById($id,'orders_express');

        $where['and']['=']['shop_express_no'] = $OrderExpressData['shop_express_no'];
        $expressData = $this->model->getItemByOther($where,'express_data');

        $_express_type = Data::$_express_type;
        $OrderExpressData['express_data'] = $expressData;
        $OrderExpressData['express_type_data'] = $_express_type;
        echo json_encode($OrderExpressData);
    }


    /*
     * 新增指派， 把指派信息存到 orders_express ,  orders status 改为未推送
     */
    public function settingExpressAction() {
        $table = "orders_express";
        $order_id = (!empty($this->params['order_id'])) ? (int)$this->params['order_id'] : '';
        $express_type = (!empty($this->params['express_type'])) ? $this->params['express_type'] : '';
        $shop_delivery_time = (!empty($this->params['shop_delivery_time'])) ? $this->params['shop_delivery_time'] : '';
        $shop_pickup_time = (!empty($this->params['shop_pickup_time'])) ? $this->params['shop_pickup_time'] : '';
        $shop_weight_gram = (!empty($this->params['shop_weight_gram'])) ? ($this->params['shop_weight_gram']) : '0';
        $shop_express_remark = (!empty($this->params['shop_express_remark'])) ? ($this->params['shop_express_remark']) : '';
        $tip = (!empty($this->params['tip'])) ? ($this->params['tip']) : '';
        $tip_remark = (!empty($this->params['tip_remark'])) ? ($this->params['tip_remark']) : '';
        $jrd_type = (!empty($this->params['jrd_type'])) ? ($this->params['jrd_type']) : '';
        $sf_push_type = (!empty($this->params['sf_push_type'])) ? ($this->params['sf_push_type']) : '';
        $is_direct_delivery = (!empty($this->params['is_direct_delivery'])) ? (int)($this->params['is_direct_delivery']) : 0;
        $notice_consignee = (!empty($this->params['notice_consignee'])) ? (int)($this->params['notice_consignee']) : '';

        $ajax_json=array("status"=>0, "msg"=>'操作有误');
        if (empty($order_id)||empty($express_type)||empty($shop_delivery_time)||empty($shop_weight_gram)){
            $ajax_json=array("status"=>0, "msg"=>'参数有误!');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        if($tip){
            if(!trim($tip_remark)){
                $ajax_json=array("status"=>0, "msg"=>'小费备注有误');
                echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
            }
        }

        $order = $this->model->getItemById($order_id,"orders");
        if($order['status'] > 0 ){
            $logs = array();
            $logs['table_id'] = $order['id'];
            $logs['table_name'] = 'orders';
            $logs['type'] = "ERROR";
            $logs['page'] = "该订单已被指派";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, $order, array());
            $ajax_json=array("status"=>0, "msg"=>'该订单已被指派');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $where = array('AND'=>array('='=>array('store_id'=>$order['shop_no'])));
        $shops = $this->model->getItemByOther($where,'xd_store');
        if($express_type !== 'self'){
            if($express_type == 'sf'){
                if(!$sf_push_type){
                    $ajax_json = array("status"=>0, "msg"=>'请选择推送顺丰商品类型');
                    echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
                }
            }
            $field=array();
            if($express_type == 'dd'){
                if($is_direct_delivery != 0 && $is_direct_delivery != 1){
                    $ajax_json = array("status"=>0, "msg"=>'请选择推送达达配送方式');
                    echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
                }
                $field['is_direct_delivery'] =  $is_direct_delivery;
            }

            $where_com = array('AND'=>array('='=>array('code'=>$shops[0]['company_id'])));
            $xd_company = $this->model->getItemByOther($where_com,'xd_company');

            $ret = $this->model->judgeExp($xd_company,$express_type);
            if($ret == false){
                $ajax_json = array("status"=>0, "msg"=>'分司/门店快递参数有误或门店手机号未填写');
                echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
            }
        }

        if (empty($order) || $order['isdeleted'] == 1){
            $ajax_json=array("status"=>0, "msg"=>'操作有误，订单不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $status = '';
        if($express_type == 'self' && $this->params['ridername'] == ''){
            $field['express_fee'] = $this->params['shop_rider_fee'];
            $field['express_courier'] = '';
            $field['express_mobile'] = '';
            $field['status'] = 2;
            $field['QRCode'] = rand(0,999999);
            $status = 2;
        }elseif($express_type == 'self' && $this->params['ridername']){
            # 微信通知
            $Config = Config::getInstance();
            $webSite = $Config->getWebSiteConfig();
            $tid = 'S000008';
            $d['c'] = 'zhaipei';
            $d['tid'] = $tid;
            $sendC = new SendSMSClass();
            $TemplateData = $sendC->getTemplateData($webSite['debug'],$d);
            $TemplateData = json_decode($TemplateData,true);
            if($TemplateData['errorcode'] == 0){
                $riderNames =  $this->params['ridername'];
                $field['status'] = 3;
                $riderName = explode('_',$riderNames);
                $field['express_courier'] = $riderName[1];
                $field['express_mobile'] = $riderName[2];
                $field['express_fee'] = $this->params['shop_rider_fee'];
                $field['QRCode'] = rand(0,999999);
                $status = 3;
                $where_field_edit = array("AND" => array("=" => array('createid' => $_SESSION['zp_shop']['store_id'], 'isdeleted' => 0, 'status' => 1, 'orders_id' => $order['id'])));
                $shop_delivery_address = $this->model->getItemByOther($where_field_edit,'shop_delivery_address');
                if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0 ){
                    $receiver_address = $shop_delivery_address[0]['receiver_address'];
                }else{
                    $receiver_address = $order['receiver_address'];
                }

                $first = '有一笔订单指派给您，请尽快前往骑手端查看！';
                $remark = '请尽快前往门店取货配送！';
                $SendData['c'] = 'zhaipei';
                $SendData['tid'] = $tid;
                $SendData['phoneNumber'] = $riderName[2];
                $SendData['contentVar']['sms']['first'] = $first;
                $SendData['contentVar']['sms']['keyword1'] = $order['shop_name'];
                $SendData['contentVar']['sms']['keyword2'] = $shops[0]['front_area'].$shops[0]['front_address'];
                $SendData['contentVar']['sms']['keyword3'] = $receiver_address;
                $SendData['contentVar']['sms']['keyword4'] = date('Y-m-d H:i:s');
                $SendData['contentVar']['sms']['remark'] = $remark;

                $SendData['contentVar']['wx']['first'] = $first;
                $SendData['contentVar']['wx']['keyword1'] = $order['shop_name'];
                $SendData['contentVar']['wx']['keyword2'] = $shops[0]['front_area'].$shops[0]['front_address'];
                $SendData['contentVar']['wx']['keyword3'] = $receiver_address;
                $SendData['contentVar']['wx']['keyword4'] = date('Y-m-d H:i:s');
                $SendData['contentVar']['wx']['remark'] = $remark;
                $s = $sendC->sendSMS($webSite['debug'],$SendData);
            }else{
                $ajax_json=array("status"=>0, "msg"=>'短信模板不存在',"fun"=>'reload');
                echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
            }
            file_put_contents('logs/sendSMS'.date('Y-m-d').'.log', date('Y-m-d H:i:s') . '  reception：' . $s . PHP_EOL, FILE_APPEND);
            $s = json_decode($s,true);
            if($s['errorcode'] == 0){
                $data['title'] = "您有一个新指派任务！";
                $data['text'] =  $_SESSION['zp_shop']['store_name'].'于'.date('Y-m-d H:i:s',time()).'为您推送了一份订单，请到待取货页面查看订单详情，尽快到门店取货';
                $data['status'] = 3;
                $data['ico'] = 1;
                $data['riders_tel'] = $riderName[2];
                $data['createdt'] = 'now()';
                $data['create_id'] = $_SESSION['zp_shop']['store_id'];
                $r = $this->model->addItem($data, 'news');
                //日志
                $logs = array();
                $logs['table_id'] = $r;
                $logs['table_name'] = 'news';
                $logs['type'] = "ADD";
                $logs['page'] = "指派骑手";
                $logs['content'] = $logs['page'] . "：" . 1;
                $this->model->setLog_SHOP($logs, array(), $data);
            }

        }else{
            $field['status']=1; //未推送
        }
        $field['orders_id'] = $order_id;
        $field['shop_no'] = $order['shop_no'];
        $field['ph_no'] =$order['ph_no'];
        $field['order_no'] =$order['order_no'];
        $field['express_type'] = $express_type;
        $field['shop_delivery_time'] = $shop_delivery_time;
        $field['shop_pickup_time'] = date('Y-m-d H:i:s',strtotime('-40 Minute',strtotime($shop_delivery_time)));
        $field['shop_goods_weight'] = $shop_weight_gram;
        $field["isdeleted"] = 0;
        $field['createdt'] = 'now()';
        $field['create_id'] =  $_SESSION['zp_shop']['store_id'];
        $field['shop_express_remark'] =  $shop_express_remark;
        $field['jrd_type'] =  $jrd_type ? $jrd_type : 2;
        $field['sf_push_type'] =  $sf_push_type;
        if($notice_consignee == 1) $field['notice_consignee'] =  $notice_consignee;

        if($tip){
            $field['tip'] =  $tip;
            $field['tip_remark'] =  $tip_remark;
        }

        $where_exp = array("AND" => array("=" => array('create_id' => $_SESSION['zp_shop']['store_id'], 'isdeleted' => 0, 'orders_id' => $order['id'],'ph_no'=>$order['ph_no'])));
        $where_exp['AND']['>']['status'] = 0;
        $where_exp['AND']['<']['status'] = 8;
        $ExpOrder = $this->model->getItemByOther($where_exp,$table);
        if($ExpOrder){
            $ErrorID = '';
            foreach ($ExpOrder as $eid){
                $ErrorID.='-'.$eid['id'];
            }
            $logs = array();
            $logs['table_id'] = $ErrorID;
            $logs['table_name'] = $table;
            $logs['type'] = "ERROR";
            $logs['page'] = "该订单已被指派";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, $order, $field);
            $ajax_json=array("status"=>0, "msg"=>'该订单已被指派');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $express_order_id = $this->model->addItem($field, $table);
        //日志
        $logs = array();
        $logs['table_id'] = $express_order_id;
        $logs['table_name'] = $table;
        $logs['type'] = "ADD";
        $logs['page'] = "指派订单";
        $logs['content'] = $logs['page'] . "：" . 1;
        $this->model->setLog_SHOP($logs, $order, $field);

        if (!empty($express_order_id)){
            //更新订单状态
            $field = array();
            if($status){
                $field['status'] = $status;
            }else{
                $field['status'] = 1;
            }
            $field['updatedt'] = 'now()';
            $field['express_type'] = $express_type;
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $order_id, "isdeleted" => 0)));
            $r = $this->model->updateItem($field, $where_fields, 'orders');
            //日志
            $logs = array();
            $logs['table_id'] = $order_id;
            $logs['table_name'] = 'orders';
            $logs['type'] = "UPDATE";
            $logs['page'] = "修改订单表状态";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, array(), $field);


            $field = array();
            $field['shop_express_no'] = $shop_express_no = $order['shop_no'].'_'.$order['ph_no'].'_'.$express_order_id;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where_fields = array("AND" => array("=" => array('id' => $express_order_id, "isdeleted" => 0)));
            $r = $this->model->updateItem($field, $where_fields, 'orders_express');

            # 新增小费清单
            if($tip && $tip_remark){
                $tips['shop_no'] = $order['shop_no'];
                $tips['order_no'] = $shop_express_no;
                $tips['price'] = $tip;
                $tips['tip_remark'] = $tip_remark;
                $tips['push_state'] = 3;
                $this->model->addItem($tips, 'tip_list');
            }

            if($status>1){
                # 新增配送信息
                $express_order['shop_express_no'] = $order['shop_no'].'_'.$order['ph_no'].'_'.$express_order_id;
                $express_order['express_order_no'] = '';
                $express_order['express_type'] = $express_type;
                $expd = $this->model->addExpressData($express_order,$status);
                if($status == 3 && $expd){
                    $fieldExpData = array();
                    $fieldExpData['express_code'] = 200;
                    $fieldExpData['express_code_desc'] = '自建骑手抢单成功';
                    $fieldExpData['express_data'] = '';
                    $fieldExpData['result_code'] = 0;
                    $this->model->updateExpressData($expd,$fieldExpData);
                }
            }
            $ajax_json=array("status"=>1, "msg"=>'操作成功',"fun"=>'reload');
        }
        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
    }

    /*
    * 删除订单，将订单设定 isdeleted=1 , orders_express的也要设定 isdeleted=1
    */
    public function delorderAction() {
        $table = "orders";
        $order_id = (!empty($this->params['del_order_id'])) ? (int)$this->params['del_order_id'] : '';

        if (empty($order_id)){
            $ajax_json=array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $order = $this->model->getItemById($order_id,$table);
        if (empty($order) || $order['isdeleted'] == 1){
            $ajax_json=array("status"=>0, "msg"=>'操作有误，订单不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }
        $field=array();
        $field['isdeleted'] = 1;
        $field['updatedt'] = 'now()';
        $field['update_id'] = $_SESSION['zp_shop']['store_id'];
        $where_fields = array("AND" => array("=" => array('id' => $order_id)));
        $r_o = $this->model->updateItem($field, $where_fields, $table);

        //日志
        $logs = array();
        $logs['table_id'] = $order['id'];
        $logs['table_name'] = $table;
        $logs['type'] = "DEL";
        $logs['page'] = "删除订单";
        $logs['content'] = $logs['page'] . "：" . 1;
        $this->model->setLog_SHOP($logs, $order, $field);

        $where_fields = array("AND" => array("=" => array('orders_id' => $order_id)));
        $where = array('AND'=>array('='=>array('orders_id' => $order_id)));
        $orders_express = $this->model->getItemByOther($where,'orders_express');
        $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
        //日志
        $logs = array();
        $logs['table_id'] = $orders_express[0]['id'];
        $logs['table_name'] = $table;
        $logs['type'] = "DEL";
        $logs['page'] = "修改订单派单表";
        $logs['content'] = $logs['page'] . "：" . 1;
        $this->model->setLog_SHOP($logs, $orders_express[0], $field);
        if (!empty($r_o)) {
            $ajax_json['status'] = 1;
            $ajax_json['msg'] = '操作成功';
            $ajax_json['fun'] = 'reload';
        }
        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;

    }


    /*
     * 未推送
     */
    public function unpushAction()
    {
        $page = (!empty($this->params['page'])) ? (int)$this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);

        $SearchArr['order_status'] = 1;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        # 获取取消信息-代码
        $cancel_code = $this->GetCancelCode();
        $this->view->setVariable("cancel_code", $cancel_code);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }



    /*
   * 取消指派，将指派订单设定 isdeleted=1 , 订单状态为 status=0
   */
    public function cancelExpressOrderAction() {
        $express_order_id = (!empty($this->params['cancel_id'])) ? (int)$this->params['cancel_id'] : '';    # 指派单id
        $ridersTel = (!empty($this->params['riderstel'])) ? $this->params['riderstel'] : '';    # 骑手手机号
        $cancel = (!empty($this->params['cancel'])) ? $this->params['cancel'] : '';    # 取消信息代码
        $cancelInfo = (!empty($this->params['cancelinfo'])) ? $this->params['cancelinfo'] : '';    # 取消信息 其他
        $ajax_json = array("status"=>0, "msg"=>'操作有误');
        if (empty($express_order_id)){
            $ajax_json = array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $express_order = $this->model->getItemById($express_order_id,"orders_express");

        $orders_no = $express_order['order_no'];
        if (empty($express_order) || $express_order['isdeleted'] == 1){
            $ajax_json=array("status"=>0, "msg"=>'操作有误，指派订单不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $del_express = false;
        if($express_order['express_type'] == 'self'){
            $del_express[0] = true;
        }else{
            if ($express_order['status']>1 && $express_order['status'] <5) {  //2 => "待接单",3 => "待取货", 4 => "配送中"
                $del_express[0] = $this->model->cancel_order($express_order['express_type'], $express_order['shop_express_no'], $express_order['express_order_no'],$cancel,$cancelInfo,$express_order['shop_no'],$orders_no);


            }else if ($express_order['status']==0 || $express_order['status'] ==1){//0 => "待指派",1 => "未推送"
                $del_express[0] = true;
            }
        }


        if ($del_express[0]){
            $field = array();
            $field['status'] = 0;
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where = array('AND'=>array('='=>array('id' => $express_order['orders_id'])));
            $orders = $this->model->getItemByOther($where,'orders');
            $where_fields = array("AND" => array("=" => array('id' => $express_order['orders_id'])));
            $r_o = $this->model->updateItem($field, $where_fields, 'orders');

            //日志
            $logs = array();
            $logs['table_id'] = $orders[0]['id'];
            $logs['table_name'] = 'orders';
            $logs['type'] = "UPDATE";
            $logs['page'] = "修改订单表";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, $orders[0], $field);

            $field = array();
            $field['status'] = 8;  //门店取消 2019-11-21 修改 统一门店取消等于快递取消状态
            $field['cancel_code'] = $cancel;  // 信息代码
            $field['updatedt'] = 'now()';
            $field['update_id'] = $_SESSION['zp_shop']['store_id'];
            $where = array('AND'=>array('='=>array('id' => $express_order['id'])));
            $orders_express = $this->model->getItemByOther($where,'orders_express');
            $where_fields = array("AND" => array("=" => array('id' => $express_order['id'])));
            $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');

            //日志
            $logs = array();
            $logs['table_id'] = $orders_express[0]['id'];
            $logs['table_name'] = 'orders_express';
            $logs['type'] = "UPDATE";
            $logs['page'] = "修改订单派单表";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, $orders_express[0], $field);

            if($ridersTel){
                $data['title'] = "您有一条新的订单信息！";
                $data['text'] =  $_SESSION['zp_shop']['store_name'].'于'.date('Y-m-d H:i:s',time()).'取消了订单-'.$orders_no.'，请点击查看订单详情';
                $data['status'] = 7;        # 门店取消通知状态  2019-11-22 修改 所有门店再配送之前取消订单 改订单状态为8  推送骑手状态任然为7
                $data['order_no'] = $orders_no;
                $data['ico'] = 1;
                $data['riders_tel'] = $ridersTel;
                $data['createdt'] = 'now()';
                $data['create_id'] = $_SESSION['zp_shop']['store_id'];
                $this->model->addItem($data, 'news');
            }
            if (!empty($r_o) && !empty($r_e)) {
                $ajax_json['status'] = 1;
                $ajax_json['msg'] = '操作成功';
                $ajax_json['fun'] = 'reload';
            }
            echo json_encode($ajax_json, JSON_UNESCAPED_UNICODE);
            exit;
        }else{
            $ajax_json['status'] = 1;
            $ajax_json['msg'] = $del_express[1];
            $ajax_json['fun'] = 'reload';
            echo json_encode($ajax_json, JSON_UNESCAPED_UNICODE);
            exit;
        }

        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;

    }
    /**
     * 待指派，将指派订单设定 isdeleted=0 , 订单状态为 status=2
     */
    public function storelistAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);
        $SearchArr['order_status'] = 2;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        # 获取取消信息-代码
        $cancel_code = $this->GetCancelCode();
        $this->view->setVariable("cancel_code", $cancel_code);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }




    /**
     * 待骑手接单， isdeleted=0 , 订单状态为 status=3
     */
    public function waitingpickupAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);
        $SearchArr['order_status'] = 3;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        # 获取取消信息-代码
        $cancel_code = $this->GetCancelCode();
        $this->view->setVariable("cancel_code", $cancel_code);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 配送中， isdeleted=0 , 订单状态为 status=4
     */
    public function deliveryAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);
        $SearchArr['order_status'] = 4;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);
//        echo'<pre>';
//        var_dump($Info);die;
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }



    /**
     * 配送完成， isdeleted=0 , 订单状态为 status=5
     */
    public function delivery_finishAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';

        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);

        $SearchArr['order_status'] = 5;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $Info = self::GetOrdersInfo($SearchArr);
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    private function GetOrdersInfo(array $SearchArr){
        $table = "orders";
        $storeID = $_SESSION['zp_shop']['store_id'];
        $order_status = $SearchArr['order_status'];
        $page = $SearchArr['page'];
        $number_page = $SearchArr['number_page'];
        $q_phno = $SearchArr['q_phno'];
        $q_mobile = $SearchArr['q_mobile'];
        $q_from_date = $SearchArr['q_from_date'];
        $q_to_date = $SearchArr['q_to_date'];
        $isdeleted = $SearchArr['isdeleted'];

        if($order_status == 100 && $isdeleted == 1){
            $where = " o.status = $order_status AND o.isdeleted = $isdeleted AND o.shop_no = $storeID";
            if($q_from_date){
                $where .= " AND o.delivery_time >= '$q_from_date'";
            }
            if($q_from_date){
                $where .= " AND o.delivery_time <= '$q_to_date'";
            }
            if($q_phno && $q_mobile){
                $where .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR o.ph_no LIKE '%$q_phno%'  )";  //OR sda.receiver_tel LIKE '%$q_mobile%'
            }elseif ($q_mobile){
                $where .= " AND (o.receiver_tel LIKE '%$q_mobile%'  )";  //OR sda.receiver_tel LIKE '%$q_mobile%'
            }elseif ($q_phno){
                $where .= " AND  o.ph_no LIKE '%$q_phno%'";
            }

            $LEFT = '';//" LEFT JOIN  shop_delivery_address as sda ON sda.orders_id = o.id and sda.isdeleted = 0";
            $field = '';//"sda.receiver_name as sda_receiver_name ,sda.receiver_tel as sda_receiver_tel,sda.receiver_address as sda_receiver_address,sda.lat as sda_lat ,sda.lng as sda_lng,sda.distance as sda_distance,sda.id as sda_id";
            $field .= " o.id, o.pos_no,o.order_no,o.shop_no,o.ph_no,o.distance,o.lng,o.lat,o.pos_fee,o.buyer,o.receiver,o.receiver_tel,o.receiver_address,o.delivery_time,o.customre_memo,o.seller_remarks,o.status,o.buyer_mobile ,o.express_type, o.source, o.del_t ";
            $sql = "SELECT $field FROM $table as o $LEFT WHERE $where ";
            $orderby=$SearchArr['order_status'] ==5? ' ORDER  BY delivery_time DESC ':' ORDER  BY delivery_time ASC ';
            $sql.=$orderby;

            $OrdersData = $this->model->GetOrdersData($page, $number_page, $sql);
            $rsp_page_list = $OrdersData['rsp_page_list'];
            $rsp_list = $OrdersData['rsp_list'];
            $total_count = $OrdersData['total_count'];
            if (!empty($rsp_list) && count($rsp_list)>0) {
                foreach ($rsp_list as $key => $value) {
                    $where = array("AND" => array("=" => array("orders_id" => $value['id'], "status" => 1, "isdeleted" => 0)));
                    $orderby = array('id' => 'asc');
                    $column_fields_pro = 'product_no,product_name,qty';
                    $products = $this->model->getAll($where, 'orders_product', $orderby, $column_fields_pro);
                    $rsp_list[$key]['products'] = $products;
                }
            }
            $Info['rsp_list'] = $rsp_list;
            $Info['rsp_page_list'] = $rsp_page_list;
            $Info['total_count'] = $total_count;
//            echo '<pre>';
//            var_dump($Info);
            return $Info;
            exit;
        }



        $where_address_mobile='';
        if (!empty($q_mobile)){
            $where = array("AND" => array("=" => array("receiver_tel" => $q_mobile, "isdeleted" => 0)));
            $orderby=array('id'=>'asc');
            $column_fields_pro = 'orders_id';
            $shop_delivery_address=$this->model->getAll($where, 'shop_delivery_address', $orderby,$column_fields_pro);
            $address_orders_id=array();
            if (!empty($shop_delivery_address)){
                foreach($shop_delivery_address as $value){
                    $address_orders_id[]=$value['orders_id'];
                }
            }
            $where_address_mobile=!empty($address_orders_id)?" OR o.id in (".join(",", $address_orders_id).") ":'';
        }

        $where = " o.status = $order_status AND o.isdeleted = 0 AND o.shop_no = $storeID";
        if($q_from_date){
            $where .= " AND o.delivery_time >= '$q_from_date'";
        }
        if($q_from_date){
            $where .= " AND o.delivery_time <= '$q_to_date'";
        }
        if($q_phno && $q_mobile){
            $where .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR o.ph_no LIKE '%$q_phno%' $where_address_mobile )";  //OR sda.receiver_tel LIKE '%$q_mobile%'
        }elseif ($q_mobile){
            $where .= " AND (o.receiver_tel LIKE '%$q_mobile%' $where_address_mobile )";  //OR sda.receiver_tel LIKE '%$q_mobile%'
        }elseif ($q_phno){
            $where .= " AND  o.ph_no LIKE '%$q_phno%'";
        }

        $LEFT = '';//" LEFT JOIN  shop_delivery_address as sda ON sda.orders_id = o.id and sda.isdeleted = 0";
        $field = '';//"sda.receiver_name as sda_receiver_name ,sda.receiver_tel as sda_receiver_tel,sda.receiver_address as sda_receiver_address,sda.lat as sda_lat ,sda.lng as sda_lng,sda.distance as sda_distance,sda.id as sda_id";
        $field .= " o.id, o.pos_no,o.order_no,o.shop_no,o.ph_no,o.distance,o.lng,o.lat,o.pos_fee,o.buyer,o.receiver,o.receiver_tel,o.receiver_address,o.delivery_time,o.customre_memo,o.seller_remarks,o.status,o.buyer_mobile ,o.express_type, o.source ";
        $sql = "SELECT $field FROM $table as o $LEFT WHERE $where ";
        $orderby=$SearchArr['order_status'] ==5? ' ORDER  BY delivery_time DESC ':' ORDER  BY delivery_time ASC ';
        $sql.=$orderby;

        //echo $sql;
        $OrdersData = $this->model->GetOrdersData($page, $number_page, $sql);
        $rsp_page_list = $OrdersData['rsp_page_list'];
        $rsp_list = $OrdersData['rsp_list'];
        $total_count = $OrdersData['total_count'];

        if (!empty($rsp_list) && count($rsp_list)>0) {
            foreach ($rsp_list as $key => $value) {
                $where = array("AND" => array("=" => array("orders_id" => $value['id'],"status" => 1,"isdeleted" => 0)));
                $orderby=array('id'=>'asc');
                $column_fields_pro = 'product_no,product_name,qty';
                $products=$this->model->getAll($where, 'orders_product', $orderby,$column_fields_pro);
                $rsp_list[$key]['products']=$products;

                # 筛选 门店修改地址
                $where = array("AND" => array("=" => array("orders_id" => $value['id'], "isdeleted" => 0)));
                $orderby=array('id'=>'asc');
                $column_fields_pro = ' receiver_name as sda_receiver_name ,receiver_tel as sda_receiver_tel,receiver_address as sda_receiver_address,lat as sda_lat ,lng as sda_lng,distance as sda_distance,id as sda_id ';
                $shop_delivery_address=$this->model->getAll($where, 'shop_delivery_address', $orderby,$column_fields_pro);
                if(!empty($shop_delivery_address)){
                    $rsp_list[$key]['receiver_address'] = $shop_delivery_address[0]['sda_receiver_address'];
                    $rsp_list[$key]['receiver_tel'] = $shop_delivery_address[0]['sda_receiver_tel'];
                    $rsp_list[$key]['receiver'] = $shop_delivery_address[0]['sda_receiver_name'];
                    $rsp_list[$key]['distance'] = $shop_delivery_address[0]['sda_distance'];
                    $rsp_list[$key]['lat'] = $shop_delivery_address[0]['sda_lat'];
                    $rsp_list[$key]['lng'] = $shop_delivery_address[0]['sda_lng'];
                }
                $ph_no = $value['ph_no'];
                if($order_status == 0){
                    $where_exp = "isdeleted = 0 AND ph_no = '$ph_no'";
                    $column_fields_exp = 'push_response_data,status,express_type,id,shop_express_remark,shop_delivery_time,shop_goods_weight,shop_express_no,express_fee,express_order_no,express_courier,express_mobile,tip,tip_remark';
                    $sql_exp = " SELECT $column_fields_exp FROM orders_express WHERE $where_exp ";
                    $res_exp = $this->model->getAny($sql_exp);
                    $orders_express = [];
                    if (!empty($res_exp)) {
                        while ($row_exp = mysqli_fetch_array($res_exp, MYSQLI_ASSOC)) {
                            $orders_express[] = $row_exp;
                        }
                    }
                    $rsp_list[$key]['express_orders'] = $orders_express;
                }else{
                    $where_exp = "";
                    if($order_status == 1){
                        $where_exp .= "(status = 0 OR  status = $order_status) AND ";
                    }else{
                        $where_exp .= "(status = $order_status) AND ";
                    }
                    $where_exp .= "isdeleted = 0 AND ph_no = '$ph_no'";
                    $column_fields_exp = 'push_response_data,status,express_type,id,shop_express_remark,shop_delivery_time,shop_goods_weight,shop_express_no,express_fee,express_order_no,express_courier,express_mobile,tip,tip_remark';
                    $sql_exp = " SELECT $column_fields_exp FROM orders_express WHERE $where_exp ";
                    $res_exp = $this->model->getAny($sql_exp);
                    $orders_express = [];
                    if (!empty($res_exp)) {
                        while ($row_exp = mysqli_fetch_array($res_exp, MYSQLI_ASSOC)) {
                            $orders_express[] = $row_exp;
                        }
                    }
                    if($orders_express && count($orders_express) > 0){
                        $rsp_list[$key]['push_response_data'] = $orders_express[0]['push_response_data'];
                        $rsp_list[$key]['exp_status'] = $orders_express[0]['status'];
                        $rsp_list[$key]['exp_express_type'] = $orders_express[0]['express_type'];
                        $rsp_list[$key]['exp_id'] = $orders_express[0]['id'];
                        $rsp_list[$key]['shop_express_remark'] = $orders_express[0]['shop_express_remark'];
                        $rsp_list[$key]['shop_delivery_time'] = $orders_express[0]['shop_delivery_time'];
                        $rsp_list[$key]['shop_goods_weight'] = $orders_express[0]['shop_goods_weight'];
                        $rsp_list[$key]['shop_express_no'] = $orders_express[0]['shop_express_no'];
                        $rsp_list[$key]['express_fee'] = $orders_express[0]['express_fee'];
                        $rsp_list[$key]['express_order_no'] = $orders_express[0]['express_order_no'];
                        $rsp_list[$key]['express_courier'] = $orders_express[0]['express_courier'];
                        $rsp_list[$key]['express_mobile'] = $orders_express[0]['express_mobile'];
                        $rsp_list[$key]['tip'] = $orders_express[0]['tip'];
                        $rsp_list[$key]['tip_remark'] = $orders_express[0]['tip_remark'];
                    }
                }

                # 后期多次追加小费 修改追叠加到orders_express中的tip + tip_remark 所有小费直接取指派表
            }

        }
        $Info['rsp_list'] = $rsp_list;
        $Info['rsp_page_list'] = $rsp_page_list;
        $Info['total_count'] = $total_count;
        return $Info;
    }
    /**
     * 配送完成导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function Error_exportAction(){
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $t = (!empty($this->params['t'])) ?  $this->params['t'] : 0;                                            # 0=未指派 1=未推送 2=待骑手接单 3=待取货 4=配送中订单 5=配送完成 6=异常 目前要求值导出配送完成的订单 其他为拓展指令
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';     # 配货单号
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';   # 收货人手机号
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';  # 预计送达时间
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        if(!$t){
            Tools::AlertTxt('?md=' . MvcReg::$_moduleName . '&cl=' . MvcReg::$_controllerName . '&at=delivery_finish'.'','系统参数错误');
            return;
        }
        $shop = $_SESSION['zp_shop']['store_id'];
        $where_fields = "o.shop_no = $shop AND o.status = $t AND o.isdeleted = 0 ";
        $where_fields2 = "o.shop_no = $shop AND o.status = $t AND o.isdeleted = 0 ";
        $where_fields_like = '';
        if($q_phno && $q_mobile){
            $where_fields_like.= " AND (o.ph_no like '%$q_phno%' OR o.receiver_tel like '%$q_mobile%')";
        }elseif($q_phno){
            $where_fields_like.= " AND o.ph_no like '%$q_phno%'";
        }elseif($q_mobile){
            $where_fields_like.= " AND o.receiver_tel like '%$q_mobile%'";
        }


        if($q_from_date){
            $where_fields.= " AND o.delivery_time >= '$q_from_date'";

        }
        if($q_from_date){
            $where_fields.= " AND o.delivery_time <= '$q_to_date'";

        }
        $where_fields_like3 = '';
        if($q_phno && $q_mobile){
            $where_fields_like3 .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR o.ph_no LIKE '%$q_phno%' OR sda.receiver_tel LIKE '%$q_mobile%')";
        }elseif ($q_mobile){
            $where_fields_like3 .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR sda.receiver_tel LIKE '%$q_mobile%')";
        }elseif ($q_phno){
            $where_fields_like3 .= " AND  o.ph_no LIKE '%$q_phno%'";
        }

        $total_count=0;
        $sql = " SELECT count(o.id) as count  FROM orders as o WHERE $where_fields2 $where_fields_like";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $total_count = $row['count'];
            }
        }
        $rsp_list=array();
        $number_page=500;
        $sel = "exp.express_fee,exp.push_response_data,exp.order_no,exp.ph_no,exp.push_response_data,exp.status,exp.express_type,exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time,
        exp.shop_goods_weight,exp.express_courier,exp.express_mobile,exp.express_order_no,exp.shop_delivery_address,exp.tip, exp.tip_remark,exp.shop_express_remark,op.product_name,o.* ,sda.receiver_name as sda_receiver_name ,sda.receiver_tel as sda_receiver_tel,sda.receiver_address as sda_receiver_address,sda.lat as sda_lat ,sda.lng as sda_lng,sda.distance as sda_distance,sda.id as sda_id";
        $total_page=floor($total_count/$number_page)+1;
        $LEFT = " LEFT JOIN  ( SELECT receiver_name,receiver_tel,receiver_address,lat,lng,distance,id,orders_id FROM shop_delivery_address where isdeleted = 0 AND status = 1 ) as sda ON sda.orders_id = o.id ";
        for($page=1;$page<=$total_page;$page++) {
             $sql = "SELECT  $sel FROM orders as o 
        LEFT JOIN orders_express as exp ON o.ph_no = exp.ph_no and o.status = exp.status
        LEFT JOIN ( SELECT  max(id) id, ph_no FROM orders_express GROUP BY ph_no ) as temp ON o.ph_no = temp.ph_no 
        LEFT JOIN (SELECT orders_id,group_concat(concat(product_name,'X',qty)) as product_name FROM orders_product GROUP BY orders_id) as op ON op.orders_id = o.id
        $LEFT WHERE $where_fields $where_fields_like3";

             $offset = ($page - 1) * $number_page;
             $limit = ' LIMIT  ' . $offset . ', ' . $number_page . ' ';
             $sql .= $limit;

             $res = $this->model->getAny($sql);
             if (!empty($res)) {
                 while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                     $rsp_list[] = $row;
                 }
             }
         }

        $where_cancel = array("AND" => array("=" => array("store_id" => $shop,"isdeleted" => 0)));
        $orderby_cancel = array('id'=>'asc');
        $store = $this->model->getAll($where_cancel, 'xd_store', $orderby_cancel);
        $store_item=array();
        if (!empty($store)){
            $store_item=$store[0];
        }
        if($rsp_list){
            foreach ($rsp_list as &$rlt){
                $distance = (!empty($rlt['sda_distance'])?$rlt['sda_distance']:$rlt['distance']);
                if($rlt['express_type'] == 'self'){
                    $distance = (!empty($rlt['sda_distance'])?$rlt['sda_distance']:$rlt['distance']);
                }elseif($rlt['express_type'] == 'sf'){
                    $exp_res = json_decode($rlt['push_response_data'],true);
                    $distance = isset($exp_res['result'])? $exp_res['result']['delivery_distance_meter']:$rlt['distance'];
                }elseif($rlt['express_type'] == 'ss'){
                    $exp_res = json_decode($rlt['push_response_data'],true);
                    $distance = isset($exp_res['data']) && count($exp_res['data'])>0? $exp_res['data'][0]['distanceTotal']:$rlt['distance'];
                }elseif($rlt['express_type'] == 'dd'){
                    $exp_res = json_decode($rlt['push_response_data'],true);
                    $distance = isset($exp_res['result'])? $exp_res['result']['distance']:$rlt['distance'];
                }
                $rlt['distance'] = round($distance/1000,2);
            }

        }

        if($rsp_list && is_array($rsp_list) && count($rsp_list) > 0) {
            $titles = array('序号', '订单编号', '订单来源', '订单清单',   '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人', '收货地址', '派单单号',
                '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态','距离', '运费', '小费','小费备注','指派备注','操作时间');
            $tableName = $store_item['storename']."_订单列表_".date('YmdHis');
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($rsp_list as $key => $row) {
                $seller_remarks = Tools::clearSymbolForCSV($row['seller_remarks']);
                $customre_memo = Tools::clearSymbolForCSV($row['customre_memo']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }


                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $customre_memo;
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $distance = ($row['distance'] > 0)?$row['distance'].'千米':'';
                if($row['sda_id']){
                    $receiver = $row['sda_receiver_name'];
                    $receiver_address = $row['sda_receiver_address'];
                }else{
                    $receiver = $row['receiver'];
                    $receiver_address = $row['receiver_address'];
                }

                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $receiver;
                $exportIinfo['receiver_address'] = $receiver_address;


                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = empty($row['status'])?'':Data::$_express_status[$row['status']];
                $exportIinfo['distance'] =  $distance;

                $exportIinfo['express_fee'] = $row['express_fee'];
                $exportIinfo['express_fee'] = $row['express_fee'];
                $exportIinfo['tip'] = $row['tip'];
                $exportIinfo['tip_remark'] = $row['tip_remark'];
                $exportIinfo['shop_express_remark'] = $row['shop_express_remark'];
                $exportIinfo['createdt'] = $row['createdt'];




                foreach($exportIinfo as $k=>$v){
                    $v=Tools::clearSymbolForCSV($v);
                    $exportIinfo[$k]=$v;
                }

                echo implode("\t ,", $exportIinfo) . "\n";
            }
            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            ob_end_flush();
            exit;

        }else{
            Tools::GoToPrev( '没有可汇出数据');
            exit;
        }
    }



    /**
     * 异常订单, 订单状态为 status=6
     */
    public function errorlistAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';

        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);

        $q_from_date = substr($q_from_date,0,strpos($q_from_date,' '));
        $q_to_date = substr($q_to_date,0,strpos($q_to_date,' '));
        $table = "orders";
        $order_status = '(o.status = 6 OR o.status = 7)' ;
        $storeID = $_SESSION['zp_shop']['store_id'];
        $where = " $order_status AND o.isdeleted = 0 AND o.shop_no = $storeID";
        if($q_from_date){
            $where .= " AND o.delivery_time >= '$q_from_date'";
        }
        if($q_from_date){
            $where .= " AND o.delivery_time <= '$q_to_date'";
        }
        if($q_phno && $q_mobile){
            $where .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR o.ph_no LIKE '%$q_phno%' OR sda.receiver_tel LIKE '%$q_mobile%')";
        }elseif ($q_mobile){
            $where .= " AND (o.receiver_tel LIKE '%$q_mobile%' OR sda.receiver_tel LIKE '%$q_mobile%')";
        }elseif ($q_phno){
            $where .= " AND  o.ph_no LIKE '%$q_phno%'";
        }
        $ordes_express =  " LEFT JOIN  orders_express as exp ON exp.orders_id = o.id AND exp.ph_no = o.ph_no AND (exp.status = 6 OR exp.status = 7) ";
        $LEFT = " LEFT JOIN  shop_delivery_address as sda ON sda.orders_id = o.id and sda.isdeleted = 0 ";
        $field = "o.*,sda.receiver_name as sda_receiver_name ,sda.receiver_tel as sda_receiver_tel,sda.receiver_address as sda_receiver_address,sda.lat as sda_lat ,sda.lng as sda_lng,sda.distance as sda_distance,sda.id as sda_id,exp.shop_remark as exp_shop_remark,exp.is_visible as exp_is_visible,exp.error_remark as exp_error_remark,exp.id as exp_id";
        $sql = "SELECT $field FROM $table as o $LEFT $ordes_express WHERE $where order by delivery_time asc";

        $OrdersData = $this->model->GetOrdersData($page, $number_page, $sql);
        $rsp_page_list = $OrdersData['rsp_page_list'];
        $rsp_list = $OrdersData['rsp_list'];
        $total_count = $OrdersData['total_count'];

        if (!empty($rsp_list) && count($rsp_list)>0) {
            foreach ($rsp_list as $key => $value) {
                $where = array("AND" => array("=" => array("orders_id" => $value['id'],"status" => 1,"isdeleted" => 0)));
                $orderby=array('id'=>'asc');
                $products=$this->model->getAll($where, 'orders_product', $orderby);
                $rsp_list[$key]['products']=$products;

                $orders_express=$this->model->getLastExpressOrder($value['id']);
                $rsp_list[$key]['orders_express']=!empty($orders_express)?$orders_express[0]:array();
                if($value['sda_id']){
                    $rsp_list[$key]['receiver_address'] = $value['sda_receiver_address'];
                    $rsp_list[$key]['receiver_tel'] = $value['sda_receiver_tel'];
                    $rsp_list[$key]['receiver'] = $value['sda_receiver_name'];
                    $rsp_list[$key]['distance'] = $value['sda_distance'];
                    $rsp_list[$key]['lat'] = $value['sda_lat'];
                    $rsp_list[$key]['lng'] = $value['sda_lng'];
                }
            }
        }

        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 骑手管理
     */
    public function horselistAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $_riders_status_code = (!empty($this->params['_riders_status_code'])) ? $this->params['_riders_status_code'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $jkz_start = (!empty($this->params['jkz_start'])) ? $this->params['jkz_start'] : '';
        $jkz_end = (!empty($this->params['jkz_end'])) ? $this->params['jkz_end'] : '';
        $createdt = (!empty($this->params['createdt'])) ? $this->params['createdt'] : '';
        $q_name = (!empty($this->params['q_name'])) ? $this->params['q_name'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("_riders_status_code", $_riders_status_code);
        $this->view->setVariable("q_mobile", $q_mobile);
        $this->view->setVariable("q_name", $q_name);
        $this->view->setVariable("createdt", $createdt);
        $this->view->setVariable("jkz_end", $jkz_end);
        $this->view->setVariable("jkz_start", $jkz_start);
        $where_fields = 'service_shop_no = '.$_SESSION['zp_shop']['store_id'].' AND isdeleted = 0';
        if($_riders_status_code){
            $where_fields .= ' AND  status = 1 AND initiate = '.$_riders_status_code.'';
        }else{
            $where_fields .= ' AND status = 1 AND (initiate = 1 OR initiate = 2)';
        }

        if($q_mobile && $q_name){
            $where_fields .= " AND tel like '%$q_mobile%' OR name like '%$q_name%'";
        }elseif($q_name){
            $where_fields .= " AND  name like '%$q_name%'";
        }elseif($q_mobile){
            $where_fields .= " AND  tel like '%$q_mobile%'";

        }

        if($jkz_start){
            $where_fields .= " AND  jkz_start >'$jkz_start'" ;
        }

        if($jkz_end){
            $where_fields .= " AND  jkz_end >'$jkz_end'" ;
        }
        $sql = "SELECT * FROM riders  WHERE $where_fields";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $where = array("AND" => array("=" => array("status" => 1,"isdeleted" => 0,"is_parent" => 1)));
        $where['AND']['>']['parent_code']= 1;
        $orderby=array('id'=>'desc');
        $area = $this->model->getAll($where, 'area', $orderby);
        if($rsp_list){
            foreach ($rsp_list as &$v){
                foreach ($area as $a){
                    if($v['service_city'] == $a['code']){
                        $v['service_city_name'] = $a['fullname'];
                    }
                }
            }
        }

        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }



    /**
     * 骑手运费信息
     */
    public function horse_freightAction() {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $q_mobile = (!empty($this->params['q_mobile'])) ?  $this->params['q_mobile'] : '';
        $q_name = (!empty($this->params['q_name'])) ?  $this->params['q_name'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $where = '';
        if($q_mobile && $q_name){
            $where .= " AND a.express_mobile like '%$q_mobile%' OR a.express_courier like '%$q_name%'";
        }elseif($q_name){
            $where .= " AND  a.express_courier like '%$q_name%'";
        }elseif($q_mobile){
            $where .= " AND  a.express_mobile like '%$q_mobile%'";

        }

        $sql = "SELECT DISTINCT(a.express_courier) AS express_courier,a.id,a.express_mobile,SUM(a.express_fee) AS fee,COUNT(*) AS num,b.storename,b.front_city,b.front_area FROM orders_express AS a LEFT JOIN xd_store AS b ON a.shop_no = b.store_id WHERE a.isdeleted = 0 AND a.status = 5 AND express_type = 'self' $where GROUP BY  a.express_mobile";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $rsp_list = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($rsp_list)) {
            while ($row = mysqli_fetch_array($rsp_list, MYSQLI_ASSOC)) {
                $res[] = $row;
            }
        }

        $this->view->setVariable("rsp_list", $res);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("q_mobile", $q_mobile);
        $this->view->setVariable("q_name", $q_name);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 骑手详情
     */

    public function horselist_checkAction(){
        $table = "riders";
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $exp_where['AND']['=']['id'] = $id;
        $rsp_list = $this->model->getItemById($id,$table);
        $orderby = array('id' => 'asc');
        $like_fields = [];
        $where['AND']['=']['status'] = 1;
        $province = $this->model->getAll($where,'area',$orderby,$like_fields);


        $orderby = array('id' => 'asc');
        $like_fields = array();
        $where['AND']['=']['status'] = 2;
        $where['OR']['=']['status'] = 4;
        $where['OR']['=']['status'] = 5;
        $store = $this->model->getAll($where,'xd_store',$orderby,$like_fields);
        $this->view->setVariable("s", 7);
        $this->view->setVariable("store", $store);
        $this->view->setVariable("province", $province);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 骑手运费详细信息
     */
    public function horse_freight_checkAction() {
        $tel = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $q_from_date = (!empty($this->params['q_from_date'])) ?  $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ?  $this->params['q_to_date'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        if($q_from_date){
             $where_fields = "updatedt >= '$q_from_date  00:00:00' AND ";
        }

        if($q_to_date){
            $where_fields .= "updatedt < '$q_to_date 23:59:59' AND ";
        }

        $sql = "SELECT * FROM orders_express  WHERE  $where_fields isdeleted = 0 AND (status = 5  OR status = 6 OR status = 0 OR status = 7) AND express_type = 'self' AND express_mobile = $tel  order BY updatedt desc";
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }

        $this->view->setVariable("s", 8);
        $this->view->setVariable("express_courier", $rsp_list[0]['express_courier']);
        $this->view->setVariable("express_mobile", $tel);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 骑手停用/查看
     */
    public function horseAction() {
        $express_id = (!empty($this->params['horse_id'])) ? (int)$this->params['horse_id'] : '';
        $type = (!empty($this->params['type'])) ? (int)$this->params['type'] : '';
        if (empty($express_id)){
            $ajax_json = array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $expressInfo = $this->model->getItemById($express_id,'riders');
        if (empty($expressInfo) || $expressInfo['isdeleted'] == 1){
            $ajax_json = array("status"=>0, "msg"=>'操作有误，该骑手不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }else{
            $where_fields = array("AND" => array("=" => array('id' => $express_id)));
            if($expressInfo['initiate'] == 1){
                $field['initiate'] = 2;
            }else{
                $field['initiate'] = 1;
            }
            $field['updatedt'] = 'now()';
            $r_e = $this->model->updateItem($field, $where_fields, 'riders');

            //日志
            $logs = array();
            $logs['table_id'] = $expressInfo['id'];
            $logs['table_name'] = 'riders';
            $logs['type'] = "UPDATE";
            $logs['page'] = "修改骑手状态表";
            $logs['content'] = $logs['page'] . "：" . 1;
            $this->model->setLog_SHOP($logs, $expressInfo, $field);
        }

        if($r_e){
            $ajax_json = array("status"=>1, "msg"=>'操作成功');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }
    }

    /**
     * 门店异常订单备注
     */
    public function remarksExpressOrderErrorAction(){
        $express_id = (!empty($this->params['error_remarks_id'])) ? (int)$this->params['error_remarks_id'] : '';
        $ajax_json = array("status"=>0, "msg"=>'操作有误');
        $remarks_error  = (!empty($this->params['remarks_error'])) ? $this->params['remarks_error'] : '';   # 异常备注信息
        $radio  = (!empty($this->params['radio'])) ? (int)$this->params['radio'] : '';   # 异常备注信息

        if (empty($remarks_error)){
            $ajax_json = array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        if (empty($express_id)){
            $ajax_json = array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $expressInfo = $this->model->getItemById($express_id,"orders_express");
        if (empty($expressInfo) || $expressInfo['isdeleted'] == 1){
            $ajax_json = array("status"=>0, "msg"=>'操作有误，配送中订单不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $field=array();
        $field['shop_remark'] = $remarks_error;
        $field['updatedt'] = 'now()';
        $field['update_id'] = $_SESSION['zp_shop']['store_id'];
        $field['is_visible'] = $radio;
        $field['status'] = 7;

        $fieldo['updatedt'] = 'now()';
        $fieldo['update_id'] = $_SESSION['zp_shop']['store_id'];
        $fieldo['status'] = 7;

        $where_fields = array("AND" => array("=" => array('id' => $express_id)));
        $where_fieldo = array("AND" => array("=" => array('ph_no' => $expressInfo['ph_no'])));
        $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
        $r_o = $this->model->updateItem($fieldo, $where_fieldo, 'orders');
        if (!empty($r_e)) {
            $ajax_json['status'] = 1;
            $ajax_json['msg'] = '操作成功';
            $ajax_json['fun'] = 'reload';
        }
        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
    }

    /**
     * 门店 配送中订单备注 回异常表
     */
    public function remarksExpressOrderAction() {
        $express_id = (!empty($this->params['remarks_id'])) ? (int)$this->params['remarks_id'] : '';
        $ajax_json = array("status"=>0, "msg"=>'操作有误');
        $error_remarks_val  = (!empty($this->params['remarks_shop'])) ? $this->params['remarks_shop'] : '';   # 异常备注信息
        if (empty($express_id)){
            $ajax_json = array("status"=>0, "msg"=>'参数有误');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $expressInfo = $this->model->getItemById($express_id,"orders_express");
        if (empty($expressInfo) || $expressInfo['isdeleted'] == 1){
            $ajax_json = array("status"=>0, "msg"=>'操作有误，配送中订单不存在');
            echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
        }

        $field=array();
//        $field['shop_remark'] = $error_remarks_val;
        $field['updatedt'] = 'now()';
        $field['update_id'] = $_SESSION['zp_shop']['store_id'];
        $field['status'] = 6;
        $where_fields = array("AND" => array("=" => array('id' => $express_id)));
        $where_fieldo = array("AND" => array("=" => array('ph_no' => $expressInfo['ph_no'])));
        $r_e = $this->model->updateItem($field, $where_fields, 'orders_express');
        $this->model->updateItem($field, $where_fieldo, 'orders');
        if (!empty($r_e)) {
            $ajax_json['status'] = 1;
            $ajax_json['msg'] = '操作成功';
            $ajax_json['fun'] = 'reload';
        }
        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
    }

    public function getErrorAction(){
        $express_id = (!empty($this->params['id'])) ? (int)$this->params['id'] : '';   # id
        $r_e = $this->model->getItemById($express_id, 'orders_express');
        echo json_encode($r_e);
    }

    public function ExportExcelAction(){
        $table = "orders_express";
        $tableName = '骑手运费.csv';
        $tel = empty($this->params["phone"]) ? '' : $this->params["phone"];
        $name = empty($this->params["name"]) ? '' :  $this->params["name"];
        $q_from_date = (!empty($this->params['q_from_date'])) ?  $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ?  $this->params['q_to_date'] : '';

        //抓列表
        $where_fields = array("AND" => array("=" => array("isdeleted" => 0,'status' => 5)));
        $where_fields['AND']['=']['express_mobile'] = $tel;
        $where_fields['AND']['=']['express_courier'] = $name;


        if($q_from_date){
            $where_fields['AND']['>=']['updatedt'] = $q_from_date;
        }

        if($q_to_date){
            $where_fields['AND']['<']['updatedt'] = $q_to_date;
        }

        $orderby = array('id' => 'asc');
        $like_fields = [];
        $data = $this->model->getAll($where_fields, $table,$orderby, $like_fields);
        if($data && is_array($data) && count($data) > 0 ){
            $titles = array('序号','骑手姓名','配货单号','运费金额','完成时间');
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t", $titles),"\n";

            foreach ($data as $key=>$value) {
                $row = array();
                $k = $key+1;
                $row['id']                    = $k;
                $row['express_courier']       = $value['express_courier'];
                $row['ph_no']                   = $value['ph_no'];
                $row['express_fee']           = $value['express_fee'];
                $row['updatedt']              = $value['updatedt'];
                echo implode("\t", $row),"\n";
            }
            header('Content-Disposition: attachment; filename='.$tableName. ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:application/vnd.ms-excel');
            ob_end_flush();
        }
    }


    /**
     * 门店 修改收货人信息
     */
    public function edit_addressAction()
    {
        $table = 'shop_delivery_address';
        $field = $this->params['receiver'];
        $field['createdt'] = 'now()';
        $field['createid'] = $_SESSION['zp_shop']['store_id'];
        $field['status'] = 1;

        unset($field['order_no']);
            if ($field && count($field) > 0) {
                $orders = $this->model->getItemById($field['orders_id'], 'orders');
                # 当前门店未指派订单
                $where['AND']['=']['orders_id'] = $field['orders_id'];
                $where['AND']['=']['status'] = 1;
                $where['AND']['=']['isdeleted'] = 0;
                $data = $this->model->getItemByOther($where, $table);

                if ($data && count($data) > 0) {
                    if ($data[0]['receiver_name'] == $field['receiver_name'] && $data[0]['receiver_tel'] == $field['receiver_tel'] && $data[0]['receiver_address'] == $field['receiver_address']) {
                        $status = 0;
                        $msg = '收货人信息已存在';
                        $ajax_json = array("status" => $status, "msg" => $msg);
                        echo json_encode($ajax_json, JSON_UNESCAPED_UNICODE);
                        exit;
                    }
                }
                if($field['receiver_address'] == $field['old_address']){
                    unset($field['old_address']);
                    if($data && count((array)$data) > 0){
                        $field['lat'] = $data[0]['lat'];
                        $field['lng'] = $data[0]['lng'];
                        $field['distance'] = $data[0]['distance'];
                    }else{
                        $field['lat'] = $orders['lat'];
                        $field['lng'] = $orders['lng'];
                        $field['distance'] = $orders['distance'];
                    }
                    $id = $this->model->addItem($field, $table);
                    $status = 1;
                    $msg = '修改成功';
                }else{
                    unset($field['old_address']);
                    $where_cancel = array("AND" => array("=" => array("store_id" => $_SESSION['zp_shop']['store_id'], "isdeleted" => 0)));
                    $orderby_cancel = array('id' => 'asc');
                    $store = $this->model->getAll($where_cancel, 'xd_store', $orderby_cancel);
                    $store_item = array();
                    if (!empty($store)) {
                        $store_item = $store[0];
                    }
                    $s_address = $store_item['front_province'] . $store_item['front_city'] . $store_item['front_area'] . $store_item['front_address'];
                    $s = $this->EXGold($s_address);
                    $distance = 0;
                    $o = $this->EXGold($field['receiver_address']);
                    if ($s && count($s) > 0 && $o && count($o) > 0) {
                        $distance = $this->getdistanceAction($s[0], $s[1], $o[0], $o[1]);
                    }
                    $field['lat'] = $o[1];
                    $field['lng'] = $o[0];
                    $field['distance'] = $distance;
                    $id = $this->model->addItem($field, $table);
                    $status = 1;
                    $msg = '修改成功';
                }
            } else {
                $status = 0;
                $msg = '参数有误';
            }

            # 修改 之前所有指派记录
        $this->model->EditShopDateilsAddressStatus($id,$field['orders_id']);
        $ajax_json = array("status"=>$status, "msg"=>$msg);
        echo json_encode( $ajax_json, JSON_UNESCAPED_UNICODE);exit;
    }


    /**
     * 自建骑手取货二维码
     */
    public function TakeQRCodeAction(){
        $QRCode= (!empty($this->params['id'])) ? $this->params['id'] : '';
        return Tools::getQRCode($QRCode, false, $size = 10);
    }

    # 兑换高德经纬度
    private function EXGold($address){
        include_once ('plugin/GaoDeAPIClass.php');
        $log = new Logging();
        $log->lfile('EXGold');
        if(strstr($address,'(')){
            $address = strstr($address,'(',true);
        }
        if(strstr($address,'（')){
            $address = strstr($address,'（',true);
        }

        $address = str_replace(' ','',$address);
        $log->lwrite(date('Y-m-d H:i:s').'  ad：'.$address.'');
        $GaoDeAPI = new GaoDeAPI();
        $r = $GaoDeAPI->getTrapezeAction($address);
        $location = [];
        if($r && count($r) > 0){
            $location = explode(',',$r['geocodes'][0]['location']);
        }
        if($location && is_array($location) && count($location) > 1){
            $log->lwrite(date('Y-m-d H:i:s').'  res：'.json_encode($location,JSON_UNESCAPED_UNICODE).'');
            return $location;
        }else{
            return '';
        }
    }

     public function EXGoldAction(){
        include_once ('plugin/GaoDeAPIClass.php');

        $GaoDeAPI = new GaoDeAPI();
        $r = $GaoDeAPI->getTrapezeAction('上海市上海市松江区新松江路555弄6号');
        $location = [];
        if($r && count($r) > 0){
            $location = explode(',',$r['geocodes'][0]['location']);
        }
        echo '<pre>';
        var_dump($location);die;

    }

    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    /**
     * 商品重量
     */
    public function GetWeightAction(){
        $p_ids = (!empty($this->params['p_ids'])) ? $this->params['p_ids'] : '';
        $p_ids = substr($p_ids,0,strrpos($p_ids,','));
        $sql = " SELECT product_no,product_name FROM `orders_product`  WHERE product_no in ($p_ids)  group by product_no";
        $res = $this->model->getAny($sql);
        $orders_product = [];
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $orders_product[] = $row;
            }
            if($orders_product && count((array)$orders_product) > 0){
                $msg = '';
                $w = 0;
                foreach($orders_product as &$p){
                    $where = array("AND" => array("=" => array('goods_num' => $p['product_no'], 'isdeleted' => 0)));
                    $result = $this->model->getItemByOther($where, "goods_weight");
                    if($result && count((array)$result) > 0){
                        $p['goods_weight'] = $result[0]['goods_weight'];
                        $w+=$result[0]['goods_weight'];
                    }else{
                        $msg .= '产品名称为：'.$p['product_name'].'  产品名编码为：'.$p['product_no'].',';
                        $p['goods_weight'] = '';
                    }
                }
            }
        }
        if($msg){
            echo json_encode(['status'=>0,'msg'=>$msg.'请先通知总管理员维护以上商品重量']);
        }else{
            echo json_encode(['status'=>1,'w'=>$w]);
        }

    }


    /**取消代码
     * @return mixed 数组
     */
    private function GetCancelCode(){
        $where_cancel = array("AND" => array("=" => array("status" => 1,"isdeleted" => 0)));
        $orderby_cancel = array('id'=>'asc');
        $code = $this->model->getAll($where_cancel, 'cancel_code', $orderby_cancel);
        return $code;
    }



    public function orders_delAction()
    {
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;
        $q_phno = (!empty($this->params['q_phno'])) ? $this->params['q_phno'] : '';
        $q_mobile = (!empty($this->params['q_mobile'])) ? $this->params['q_mobile'] : '';
        $q_from_date = (!empty($this->params['q_from_date'])) ? $this->params['q_from_date'] : '';
        $q_to_date = (!empty($this->params['q_to_date'])) ? $this->params['q_to_date'] : '';
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $SearchArr['order_status'] = 100;
        $SearchArr['page'] = $page;
        $SearchArr['number_page'] = $number_page;
        $SearchArr['q_phno'] = $q_phno;
        $SearchArr['q_mobile'] = $q_mobile;
        $SearchArr['q_from_date'] = $q_from_date;
        $SearchArr['q_to_date'] = $q_to_date;
        $SearchArr['isdeleted'] = 1;
        $Info = self::GetOrdersInfo($SearchArr);
        $ridersWhere = array("AND" => array("=" => array("initiate" =>1,"status" =>1,'isdeleted'=>0,'service_shop_no'=>$_SESSION['zp_shop']['store_id'])));
        $orderby = array('id'=>'desc');
        $ridersList = $this->model->getAll($ridersWhere, 'riders', $orderby);
        $this->view->setVariable("ridersList", $ridersList);

        $this->view->setVariable("q_from_date", $q_from_date);
        $this->view->setVariable("q_to_date", $q_to_date);
        $this->view->setVariable("q_phno", $q_phno);
        $this->view->setVariable("q_mobile", $q_mobile);
        $this->view->setVariable("rsp_list", $Info['rsp_list']);
        $this->view->setVariable("rsp_page_list", $Info['rsp_page_list']);
        $this->view->setVariable("total_count", $Info['total_count']);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


}